package com.stx.jeepay.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.SysRoleEntRelaDao;
import com.stx.jeepay.core.entity.SysEntitlementEntity;
import com.stx.jeepay.core.entity.SysRoleEntRelaEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.service.SysEntitlementService;
import com.stx.jeepay.core.service.SysRoleEntRelaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("sysRoleEntRelaService")
public class SysRoleEntRelaServiceImpl extends ServiceImpl<SysRoleEntRelaDao, SysRoleEntRelaEntity> implements SysRoleEntRelaService {

    @Autowired
    private SysEntitlementService sysEntitlementService;

    /**
     * 根据人查询出所有权限ID集合
     */
    @Override
    public List<String> selectEntIdsByUserId(Long sysUserId, Byte isAdmin, String sysType) {
        if (isAdmin == CS.YES) {
            List<String> result = new ArrayList<>();
            sysEntitlementService.list(new LambdaQueryWrapper<SysEntitlementEntity>()
                    .select(SysEntitlementEntity::getEntId)
                    .eq(SysEntitlementEntity::getSysType, sysType)
                    .eq(SysEntitlementEntity::getState, CS.PUB_USABLE)).stream().forEach(i -> result.add(i.getEntId()));
            return result;
        } else {
            return baseMapper.selectEntIdsByUserId(sysUserId, sysType);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetRela(String roleId, List<String> entIdList) {
        //1. 删除
        remove(new LambdaQueryWrapper<SysRoleEntRelaEntity>().eq(SysRoleEntRelaEntity::getRoleId, roleId));

        //2. 插入
        for (String entId : entIdList) {
            SysRoleEntRelaEntity r = new SysRoleEntRelaEntity();
            r.setRoleId(roleId);
            r.setEntId(entId);
            save(r);
        }
    }
}